package com.qianchang.microfinance.view.home.mortgage;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;

import com.bigkoo.pickerview.model.IPickerViewData;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.BaseTextWatcher;
import com.dm.library.widgets.ClearEditText;
import com.dm.library.widgets.OneLineLinearLayout;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.LoanType;
import com.qianchang.microfinance.bean.ProductBean;
import com.qianchang.microfinance.bean.ProductMortgageBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.utils.CalUtils;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.dialog.AreaDialog;
import com.qianchang.microfinance.view.dialog.CommonDialog;
import com.qianchang.microfinance.view.home.cash.ProductIntroduceActivity;
import com.qianchang.microfinance.view.mine.intention.LoanIntentionActivity;
import com.qianchang.microfinance.view.mine.loan.RepayPlanActivity;
import com.qianchang.microfinance.view.product.ProductFragment;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 抵押贷 申请借款
 */
public class ApplyMortgageActivity extends BaseActivity implements CommonDialog.OnItemSelectListener {

    @BindView(R.id.et_apply_amount)
    ClearEditText etApplyAmount;
    @BindView(R.id.oll_payback_type)
    OneLineLinearLayout ollPaybackType;
    @BindView(R.id.oll_dateLine)
    OneLineLinearLayout ollDateLine;
    @BindView(R.id.oll_mortgage_type)
    OneLineLinearLayout ollMortgageType;
    @BindView(R.id.oll_address)
    OneLineLinearLayout ollAddress;
    @BindView(R.id.oll_interest_rate)
    OneLineLinearLayout ollInterestRate;
    @BindView(R.id.oll_total_interest)
    OneLineLinearLayout ollTotalInterest;
    @BindView(R.id.oll_loan_fee)
    OneLineLinearLayout ollLoanFee;

    private static final int FLAG_PAYBACK_METHOD = 0;
    private static final int FLAG_DEADLINE = 1;
    private static final int FLAG_MORTGATE_TYPE = 2;
    double totalInterest;
    @BindView(R.id.tv_right)
    DTextView tvRight;


    private String mProvinceId;
    private String mCityId;
    private String mCountyId;

    private String collateralType;
    private double applyAmount;
    private String serviceFeeSetting;
    private String mDeadline;
    private String lastProductUpdateTime;
    private String productId;
    private String productType;
    private int repaymentType = -1;
    private String unit;

    private ProductBean productBean;

    private List<ProductMortgageBean.DeadlineMonthListBean> deadlineMonthList;            //存放月的数据
    private List<ProductMortgageBean.RepaymentTypeBean> repaymentTypeList;                //还款方式
    private List<ProductMortgageBean.CollateralTypeBean> collateralTypeList;              //抵押物类型
    private ProductMortgageBean.ProductInfoBean productInfo;
    private double mMonthRate;
    private double applyMoneyStart;
    private double applyMoneyEnd;
    private String strRate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_mortgage);
        ButterKnife.bind(this);
        setTitleName(getString(R.string.mortgage_loan));
        initView();
        initData();
    }


    @Override
    protected void initView() {
        super.initView();
        etApplyAmount.addTextChangedListener(new BaseTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                applyAmount = StringUtils.toInt(s.toString().trim(), 0);
                if (mMonthRate != 0) {
                    setInterest();
                }
            }
        });
    }

    private void initProductIntrduce() {
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setTextContent(getString(R.string.Label_product_intrduce));
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle_product = new Bundle();
                bundle_product.putString(ConstantAppInfo.PROJECT_ID, productId);
                bundle_product.putString(ConstantAppInfo.PROJECT_TYPE, productType);
                startActivity(ProductIntroduceActivity.class, bundle_product);
            }
        });
    }


    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (null != bundle) {
            productBean = (ProductBean) bundle.getSerializable(ProductFragment.PRODUCT_BEAN);
            if (null != productBean) {
                productType = productBean.getProductType();
                productId = productBean.getProductId();
            } else {
                productType = bundle.getString(ConstantAppInfo.PROJECT_TYPE);
            }
        }
        //产品介绍
        initProductIntrduce();
        getConstantInfo();
    }

    private void getConstantInfo() {
        show();
        HttpParams params = new HttpParams();
        params.put("productType", productType); //产品类型
        params.put("productId", productId); //产品Id
        DMOKHttpUtils.getInstance().post(this, DMConstant.Config.BASE_USER + "/product/" + LoanType.getNameByType(productType) + DMConstant.Config.V + "/getConfig.do", params, new RequestCallBack<ProductMortgageBean>() {

            @Override
            public void onSuccess(JsonResult<ProductMortgageBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ProductMortgageBean productConfigBean = response.getObject();
                    if (null != productConfigBean) {
                        deadlineMonthList = productConfigBean.getDeadlineMonthList();
                        repaymentTypeList = productConfigBean.getRepaymentType();
                        collateralTypeList = productConfigBean.getCollateralType();

                        productInfo = productConfigBean.getProductInfo();
                        if (null != productInfo) {
                            applyMoneyStart = productInfo.getApplyMoneyStart();
                            applyMoneyEnd = productInfo.getApplyMoneyEnd();
                            lastProductUpdateTime = productInfo.getUpdateTime();

                            etApplyAmount.setHint("借款范围" + FormatUtil.numKbPointFormat(applyMoneyStart) + "~" + FormatUtil.numKbPointFormat(applyMoneyEnd));
                            ollLoanFee.setRightContent(FormatUtil.get2Double(productInfo.getBorrowFeeRate()*100)+"%");
                        }
                    }
                } else {
                    ToastUtil.getInstant().show(ApplyMortgageActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ApplyMortgageActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });

    }

    @OnClick({R.id.oll_payback_type, R.id.oll_dateLine, R.id.oll_mortgage_type, R.id.oll_address, R.id.oll_payback_plan, R.id.btn_submit})
    public void onViewClicked(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.oll_address:
                AreaDialog areaDialog = new AreaDialog(this);
                areaDialog.setTitle(getString(R.string.please_select_area));
                areaDialog.setOnAreaSelectListener(new AreaDialog.OnAreaSelectListener() {
                    @Override
                    public void onAreaSelect(String provinceId, String cityId, String areaId, String result) {
                        mProvinceId = provinceId;
                        mCityId = cityId;
                        mCountyId = areaId;
                        ollAddress.setRightContent(result);
                    }
                });
                areaDialog.showPickerView();
                break;
            case R.id.oll_payback_plan:
                checkAndgotoLoanPlan();
                break;
            case R.id.btn_submit:
                if (checkParams()) {
                    commitData();
                }
                break;
            default:
                clickDialog(viewId);
                break;
        }
    }

    private boolean checkParams() {
        if (applyAmount == 0) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_input_loan_amount));
            return false;
        }
        if (applyAmount > applyMoneyEnd) {
            ToastUtil.getInstant().show(this, "借款金额不能大于最大借款额度");
            return false;
        }

        if (applyAmount < applyMoneyStart) {
            ToastUtil.getInstant().show(this, "借款金额不能小于最小借款额度");
            return false;
        }

        if (-1 == repaymentType) {
            ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_mode));
            return false;
        }
        if (StringUtils.isEmptyOrNull(mDeadline)) {
            ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_deadline));
            return false;
        }

        if (0 == mMonthRate) {
            ToastUtil.getInstant().show(ApplyMortgageActivity.this, getString(R.string.data_error));
            return false;
        }

        if (TextUtils.isEmpty(collateralType)) {
            ToastUtil.getInstant().show(ApplyMortgageActivity.this, "请选择抵押物类型");
            return false;
        }

        if (TextUtils.isEmpty(mProvinceId)) {
            ToastUtil.getInstant().show(ApplyMortgageActivity.this, "请选择所在城市");
            return false;
        }

        return true;
    }

    //跳转到借款计划
    private void checkAndgotoLoanPlan() {
        if (!checkLoanPlan()) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putDouble("applyAmount", applyAmount); //借款金额
        bundle.putString("repaymentType", String.valueOf(repaymentType));// //还款方式
        bundle.putString("deadline", String.valueOf(mDeadline));    //借款期限
        bundle.putString("reta", String.valueOf(mMonthRate)); //利率（月）
        bundle.putString("serviceFeeSetting", "0"); // 是否是固定金额
        if(repaymentType == 0){
            bundle.putString("strRate", getString(R.string.Label_daily_interest_rate) + strRate); //天
        }else{
            bundle.putString("strRate", getString(R.string.Label_monthly_interest_rate) + strRate); //月
        }
        bundle.putDouble("allInterestRate", totalInterest); //总利息
        startActivity(RepayPlanActivity.class, bundle);
    }


    private boolean checkLoanPlan() {
        if (applyAmount == 0) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_input_loan_amount));
            return false;
        }
        if (-1 == repaymentType) {
            ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_mode));
            return false;
        }
        if (StringUtils.isEmptyOrNull(mDeadline)) {
            ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_deadline));
            return false;
        }

        if (0 == mMonthRate) {
            ToastUtil.getInstant().show(ApplyMortgageActivity.this, getString(R.string.data_error));
            return false;
        }
        return true;
    }


    private void commitData() {
        HttpParams params = new HttpParams();
        params.put("provinceId", mProvinceId);
        params.put("cityId", mCityId);
        params.put("countyId", mCountyId);
        params.put("collateralType", collateralType);
        params.put("applyAmount", applyAmount);
        params.put("deadline", mDeadline);
        params.put("deadlinekey", mDeadline);
        params.put("lastProductUpdateTime", lastProductUpdateTime);
        params.put("unit", unit);
        params.put("productType", productType);
        params.put("productId", productId);
        params.put("repaymentType", repaymentType);
        params.put("serviceFeeRate", mMonthRate);
        params.put("serviceFeeSetting", "1");


        DMOKHttpUtils.getInstance().post(this, DMConstant.Config.BASE_USER + "/project/" + LoanType.getNameByType(productType) + DMConstant.Config.V + "/insert.do", params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                if (response.isReqDataSuccess()) {
                    startActivity(LoanIntentionActivity.class);
                    finish();
                } else {
                    ToastUtil.getInstant().show(ApplyMortgageActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(ApplyMortgageActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void clickDialog(int viewId) {
        CommonDialog.Builder builder = new CommonDialog
                .Builder()
                .setContext(this)
                .setOnItemSelectListener(this);
        switch (viewId) {
            case R.id.oll_payback_type:
                builder.setTitle(getString(R.string.payback_method))
                        .setData(repaymentTypeList)
                        .setFlag(FLAG_PAYBACK_METHOD);
                break;
            case R.id.oll_dateLine:
                if (applyAmount == 0) {
                    ToastUtil.getInstant().show(this, "请输入借款金额");
                    return;
                }
                if (-1 == repaymentType) {
                    ToastUtil.getInstant().show(this, "请选择还款方式");
                    return;
                }

                builder.setTitle(getString(R.string.repay_deadline))
                        .setData(deadlineMonthList)
                        .setFlag(FLAG_DEADLINE);
                break;
            case R.id.oll_mortgage_type:
                builder.setTitle(getString(R.string.payback_method))
                        .setData(collateralTypeList)
                        .setFlag(FLAG_MORTGATE_TYPE);
                break;
        }
        builder.build().showPickerView();
    }

    @Override
    public void onItemSelect(IPickerViewData data, int position, int flag) {
        String name = data.getPickerViewText();
        switch (flag) {
            case FLAG_DEADLINE:
                ProductMortgageBean.DeadlineMonthListBean deadlineMonthListBean = (ProductMortgageBean.DeadlineMonthListBean) data;
                mDeadline = deadlineMonthListBean.getMonth();
                mMonthRate = deadlineMonthListBean.getMonthRate();
                unit = deadlineMonthListBean.getUnit();
                strRate = FormatUtil.get2String(mMonthRate * 100) + "%";
                ollInterestRate.setRightContent(FormatUtil.formatStr2(String.valueOf(mMonthRate * 100)) + "%");
                ollDateLine.setRightContent(name);
                setInterest();
                break;
            case FLAG_MORTGATE_TYPE:
                ProductMortgageBean.CollateralTypeBean collateralTypeBean = (ProductMortgageBean.CollateralTypeBean) data;
                collateralType = collateralTypeBean.getType();
                ollMortgageType.setRightContent(name);
                break;
            case FLAG_PAYBACK_METHOD:
                ProductMortgageBean.RepaymentTypeBean repaymentTypeBean = (ProductMortgageBean.RepaymentTypeBean) data;
                repaymentType = repaymentTypeBean.getType();
                ollPaybackType.setRightContent(name);
                break;
        }
    }


    public void setInterest() {
        int deadline = StringUtils.toInt(mDeadline, 0);
        switch (repaymentType) {
            case 0://一次性还款付息
                if ("1".equals(serviceFeeSetting)) { //0代表固定金额，1代表%
//                    totalInterest =
                } else {
                    totalInterest = CalUtils.calOneTimePay(applyAmount, mMonthRate, deadline);
                }
                break;
            case 1://等额本息
                totalInterest = CalUtils.calSameBenXi(applyAmount, mMonthRate, deadline);
                break;
            case 2://等额本金
                totalInterest = CalUtils.calSameBenJin(applyAmount, mMonthRate, deadline);
                break;
            case 3://每月付息，到期还本
                totalInterest = CalUtils.calEveryMonth(applyAmount, mMonthRate, deadline);
                break;
        }
        ollTotalInterest.setRightContent(FormatUtil.numKbPointFormat(totalInterest));
    }

}

